package com.wanpinghui.supplier.business.view;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Color;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.net.Uri;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.VideoView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.wanpinghui.supplier.R;
import com.wanpinghui.supplier.business.DynamicDetailActivity;
import com.wanpinghui.supplier.business.VideoPlayActivity;
import com.wanpinghui.supplier.business.adapter.CircleListAdapter;
import com.wanpinghui.supplier.message.PhotoBrowseActivity;
import com.wanpinghui.supplier.object.HomePageActivity;
import com.wanpinghui.wphlibrary.model.business.bean.ContentImg;
import com.yunshl.yunshllibrary.recyclerview.YunGridLayoutManager;
import com.yunshl.yunshllibrary.utils.DevicesUtil;
import com.yunshl.yunshllibrary.utils.ImageUtil;
import com.yunshl.yunshllibrary.utils.TextUtil;

import org.xutils.common.util.DensityUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/***
 * 功能描述:今日新款多张图显示view
 * 作者:xiongning
 * 时间:2016/12/21
 * 版本:v1.0
 ***/
public class MultiImageView extends LinearLayout {
	private List<ContentImg> datas;
	private int column = 3;
	private int screenWidth;//屏幕宽度
	private int screenHeight;//屏幕高度
	private int maxImageWidth;//单图片时最大的宽
	private int maxImageHeight;//单图片时最大的高
	private int gridViewWidth;
	private int dividerWidth;
	//private VideoView mVideoView;
	private RecyclerView recyclerView;
	private ImageView mImageView;
	private ImageAdapter mAdapter;
	private ImageView mImageViewThumbnial;
	private ImageView mImageViewControl;
	private RelativeLayout mLayoutVideo;
	private View rootView;
	private boolean isPlaying;
	private int videoHeight;
	private int videoWidth;
	private String videoUrl;
	private String videoThumb;
	private Bitmap mBitmap;
	private List<View> views;

	private CircleListAdapter circleListAdapter;

	public MultiImageView(Context context) {
		super(context);
		init();
	}

	public MultiImageView(Context context, @Nullable AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	public MultiImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		init();
	}

	public void setCircleAdapter(CircleListAdapter adapter) {
		circleListAdapter = adapter;
	}

	public void setViewWidth(int width) {
		gridViewWidth = width;
		RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) recyclerView.getLayoutParams();
		layoutParams.width = gridViewWidth;
		recyclerView.setLayoutParams(layoutParams);
	}

	public void setDatas(List<ContentImg> list) {
		datas = list;
		views.clear();
		mImageView.setImageResource(R.mipmap.loading_140x140);
		mImageViewThumbnial.setImageResource(R.mipmap.loading_140x140);
		if (datas != null && datas.size() > 1) {
			recyclerView.setVisibility(VISIBLE);
			mImageView.setVisibility(GONE);
			mLayoutVideo.setVisibility(GONE);
			if (mAdapter != null) {
				mAdapter.notifyDataSetChanged();
			}
		}else if (datas != null && datas.size() == 1){
			if (datas.get(0).getType() == ContentImg.ImgType.TYPE_PICTURE) {
				views.add(mImageView);
				recyclerView.setVisibility(GONE);
				mImageView.setVisibility(VISIBLE);
				mLayoutVideo.setVisibility(GONE);
				mImageView.setTag(datas.get(0).getThumbnailUrl());
				setPicture(datas.get(0).getThumbnailUrl());
			}else {
				views.add(mImageViewThumbnial);
				recyclerView.setVisibility(GONE);
				mImageView.setVisibility(GONE);
				mLayoutVideo.setVisibility(VISIBLE);

				setVideo(datas.get(0));
			}
		}else {
			recyclerView.setVisibility(GONE);
			mImageView.setVisibility(GONE);
			mLayoutVideo.setVisibility(GONE);
		}
	}

	private void setVideo(final ContentImg contentImg) {
		videoUrl = contentImg.getUrl();
		if (TextUtil.isNotEmpty(contentImg.getThumb_url())) {
			videoThumb = contentImg.getThumb_url()+"_thumbnail";
			Glide.with(getContext()).load(videoThumb).downloadOnly(new SimpleTarget<File>() {
				@Override
				public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) {
					Bitmap bitmap = BitmapFactory.decodeFile(resource.getAbsolutePath());
					setVideoImg(bitmap);
				}
			});
		}else {
			videoThumb = null;
			ImageUtil.createVideoThumbnail(videoUrl, new ImageUtil.CallBack() {
				@Override
				public void onSuccess(Bitmap bitmap) {
					setVideoImg(bitmap);
				}

				@Override
				public void onError() {

				}
			});
		}
	}

	private void setVideoImg(Bitmap bitmap) {
		videoWidth = bitmap.getWidth();
		videoHeight = bitmap.getHeight();
		mBitmap = bitmap;
		if (videoWidth > videoHeight) {
            int width = videoWidth;
            int height = videoHeight;
                width = maxImageWidth;
                height = (int) (videoHeight * ((float) maxImageWidth / videoWidth));
            RelativeLayout.LayoutParams layoutParams2 = (RelativeLayout.LayoutParams) mImageViewThumbnial.getLayoutParams();
            layoutParams2.height = height;
            layoutParams2.width = width;
            mImageViewThumbnial.setLayoutParams(layoutParams2);
            mImageViewThumbnial.setImageBitmap(bitmap);

            RelativeLayout.LayoutParams layoutParams3 = (RelativeLayout.LayoutParams) mImageViewControl.getLayoutParams();
            layoutParams3.height = (int) (height * 0.37);
            layoutParams3.width = (int) (height * 0.37);
            mImageViewControl.setLayoutParams(layoutParams3);
        } else {
            int width = videoWidth;
            int height = videoHeight;
                height = maxImageHeight;
                width = (int) (videoWidth * ((float) maxImageHeight / (float) videoHeight));
            RelativeLayout.LayoutParams layoutParams2 = (RelativeLayout.LayoutParams) mImageViewThumbnial.getLayoutParams();
            layoutParams2.height = height;
            layoutParams2.width = width;
            mImageViewThumbnial.setLayoutParams(layoutParams2);
            mImageViewThumbnial.setImageBitmap(bitmap);

            RelativeLayout.LayoutParams layoutParams3 = (RelativeLayout.LayoutParams) mImageViewControl.getLayoutParams();
            layoutParams3.height = (int) (width * 0.37);
            layoutParams3.width = (int) (width * 0.37);
            mImageViewControl.setLayoutParams(layoutParams3);
        }
	}

	private void setPicture(final String url) {
		Glide.with(getContext()).load(url).downloadOnly(new SimpleTarget<File>() {
			@Override
			public void onResourceReady(File resource, GlideAnimation<? super File> glideAnimation) {
				BitmapRegionDecoder mDecoder;
				try {
					mDecoder = BitmapRegionDecoder.newInstance(resource.getAbsolutePath(), false);
					if (url.equals(mImageView.getTag())) {
						// 获取原图片宽高
						int imageWidth = mDecoder.getWidth();
						int imageHeight = mDecoder.getHeight();
						if (imageWidth > imageHeight) {
							int width = imageWidth;
							int height = imageHeight;
							//if (imageWidth > maxImageWidth) {
								width = maxImageWidth;
								height = (int) (imageHeight * ((float) maxImageWidth / imageWidth));
							//}
							RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mImageView.getLayoutParams();
							layoutParams.height = height;
							layoutParams.width = width;
							mImageView.setLayoutParams(layoutParams);
							Rect rect = new Rect(0, 0, imageWidth, imageHeight);
							mBitmap = mDecoder.decodeRegion(rect, null);
							mImageView.setImageBitmap(mBitmap);
						} else {
							int width = imageWidth;
							int height = imageHeight;
							//if (imageHeight > maxImageHeight) {
								height = maxImageHeight;
								width = (int) (imageWidth * ((float) maxImageHeight / (float) imageHeight));
							//}
							RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mImageView.getLayoutParams();
							layoutParams.height = height;
							layoutParams.width = width;
							mImageView.setLayoutParams(layoutParams);
							Rect rect = new Rect(0, 0, imageWidth, imageHeight);
							mBitmap = mDecoder.decodeRegion(rect, null);
							mImageView.setImageBitmap(mBitmap);
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	private void init() {
		views = new ArrayList<>();
		LayoutInflater.from(getContext()).inflate(R.layout.view_dynamic_image_content, this);
		recyclerView = (RecyclerView) findViewById(R.id.recv_content);
		mImageView = (ImageView) findViewById(R.id.image_view);
		mImageViewControl = (ImageView) findViewById(R.id.iv_controler);
		mImageViewThumbnial = (ImageView) findViewById(R.id.iv_video_thumbnail);
		mLayoutVideo = (RelativeLayout) findViewById(R.id.rl_video);
		rootView = findViewById(R.id.root_view);
		screenWidth = DevicesUtil.getWidth(getContext());
		screenHeight = DevicesUtil.getHeight(getContext());
		maxImageWidth = (int) (screenWidth * 0.53);
		maxImageHeight = maxImageWidth;
		recyclerView.setLayoutManager(new YunGridLayoutManager(getContext(),column));
		dividerWidth = DevicesUtil.dip2px(getContext(),7.5f);
		mAdapter = new ImageAdapter();
		recyclerView.setAdapter(mAdapter);

		gridViewWidth = screenWidth - DevicesUtil.dip2px(getContext(),87);
		RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) recyclerView.getLayoutParams();
		layoutParams.width = gridViewWidth;
		recyclerView.setLayoutParams(layoutParams);
		mImageViewThumbnial.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (TextUtil.isNotEmpty(videoUrl)&&mBitmap != null) {
					VideoPlayActivity.startWithElement((Activity) getContext(), videoUrl, mImageViewThumbnial, videoThumb,videoWidth,videoHeight);
				}
			}
		});
		mImageView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				previewPhoto(0,mImageView,false);
			}
		});

	}

	private void previewPhoto(int currentIndex, View view, boolean set) {
		if (datas != null && datas.size() > 0){
			ArrayList<String> strings = new ArrayList<>();
			for (ContentImg img : datas) {
				strings.add(img.getUrl());
			}
			PhotoBrowseActivity.startWithElement((Activity)getContext(),strings,currentIndex,view,null);
			if (set) {
				try {
					if (getContext() instanceof HomePageActivity) {
						((HomePageActivity) getContext()).setSharedElementCallback((Activity) getContext());
					}else if (getContext() instanceof DynamicDetailActivity) {
						((HomePageActivity) getContext()).setSharedElementCallback((Activity) getContext());
					}
				}catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	public View getViewByIndex(int index) {
		if (views != null && views.size() > index) {
			return views.get(index);
		}
		return null;
	}

	class ImageAdapter extends RecyclerView.Adapter{

		public ImageAdapter() {
			views = new ArrayList<>();
		}

		@Override
		public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
			View view = LayoutInflater.from(getContext()).inflate(R.layout.item_gridview_dynamic_image,null);
			return new ImageHolder(view);
		}

		@Override
		public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
			int size = (int) ((gridViewWidth-(dividerWidth*(column-1))) / (float)column);
			//holder.itemView.setLayoutParams(new GridView.LayoutParams(size, size));
			if (views.size() > position) {
				views.add(position,((ImageHolder)holder).imageView);
			}else {
				views.add(((ImageHolder)holder).imageView);
			}
			RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams)((ImageHolder)holder).imageView.getLayoutParams();
			layoutParams.width = size;
			layoutParams.height = size;
			if ((position+1)%3 == 0) {
				layoutParams.rightMargin = 0;
			}else {
				layoutParams.rightMargin = DensityUtil.dip2px(7.5f);
			}

			if ((position+3)/getItemCount() == 1) {
				layoutParams.bottomMargin = 0;
			}else {
				layoutParams.bottomMargin = DensityUtil.dip2px(7.5f);
			}
			((ImageHolder)holder).imageView.setLayoutParams(layoutParams);

			((ImageHolder)holder).imageView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					if (circleListAdapter != null) {
						circleListAdapter.setViews(views);
					}
					previewPhoto(position,((ImageHolder)holder).imageView,true);
				}
			});
			Glide.with(getContext()).load(datas.get(position).getThumbnailUrl()).placeholder(R.mipmap.loading_140x140).error(R.mipmap.goods_bg_loading).into(((ImageHolder)holder).imageView);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public int getItemCount() {
			return datas == null ? 0 : datas.size();
		}

	}

	class ImageHolder extends RecyclerView.ViewHolder{
		ImageView imageView;
		public ImageHolder(View itemView) {
			super(itemView);
			imageView = (ImageView) itemView.findViewById(R.id.iv_image);
			//itemView.setLayoutParams(new GridLayoutManager.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
		}
	}
}